/*
 * SonarSource :: .NET :: Core
 * Copyright (C) 2014-2025 SonarSource Sàrl
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the Sonar Source-Available License for more details.
 *
 * You should have received a copy of the Sonar Source-Available License
 * along with this program; if not, see https://sonarsource.com/license/ssal/
 */
package org.sonarsource.dotnet.shared.plugins.protobuf;

import com.google.protobuf.Parser;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
  This class is the base class of all protobuf message importers. Those importers allow to read some information generated by the C#/VB.NET analyzers.

  Note that if the protobuf message is supposed to contain some path then you should use the ProtobufImporter class
 */
public abstract class RawProtobufImporter<T> {

  private final Parser<T> parser;

  RawProtobufImporter(Parser<T> parser) {
    this.parser = parser;
  }

  public void accept(Path protobuf) {
    try (InputStream inputStream = Files.newInputStream(protobuf)) {
      while (true) {
        T message = parser.parseDelimitedFrom(inputStream);
        if (message == null) {
          break;
        }
        consume(message);
      }
    } catch (IOException e) {
      throw new IllegalStateException("unexpected error while parsing protobuf file: " + protobuf, e);
    }
  }

  abstract void consume(T message);

  public void save() {
    // only highlight importer is using this method for now but we should expand to other importers
    // when we start merging other protobuf data
  }
}
